package main

import (
	"bytes"
	"encoding/json"
	"github.com/prometheus/alertmanager/pkg/labels"
	"github.com/prometheus/alertmanager/types"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

// 调用AlertManager的告警静默接口
func createSilence(alertMUrl string) {
	matchers := labels.Matchers{}
	m1 := &labels.Matcher{
		Type:  labels.MatchEqual,
		//我们的配置文件配置的就是node_name abc
		Name:  "node_name",
		Value: "abc",
	}
	matchers = append(matchers, m1)
	si := types.Silence{
		ID:        "",
		Matchers:  matchers,
		StartsAt:  time.Now(),
		EndsAt:    time.Now().Add(3 * time.Hour * 24),
		CreatedBy: "xiaoyi",
		Comment:   "小乙创建的告警静默",
		Status:    types.SilenceStatus{},
	}

	jsonStr, _ := json.Marshal(si)

	req, err := http.NewRequest("POST", alertMUrl, bytes.NewBuffer(jsonStr))
	if err != nil {
		return
	}
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Printf("[http.post.request.err][url:%v][err:%v]", alertMUrl, err)
		return
	}
	defer resp.Body.Close()

	log.Printf("response Status:%v", resp.Status)
	log.Printf("response Headers:%v", resp.Header)
	body, _ := ioutil.ReadAll(resp.Body)
	log.Printf("response Body:%v", string(body))

}


func main() {
	alertMUrl := "http://192.168.56.13:9093/api/v1/silences"
	createSilence(alertMUrl)

}
